/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  ZoneTuiJianFragment.java   
 * @Package com.jiyi.activity.zone   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-6-6 上午10:47:48   
 * @version V1.0     
 */
package com.jiyi.activity.zone;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.BufferType;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMMessage.Type;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.utils.EaseSmileUtils;
import com.jauker.widget.BadgeView;
import com.jiyi.adapter.DividerItemDecoration;
import com.jiyi.bean.zone.ZoneHaoYouBean;
import com.jiyi.bean.zone.ZoneHaoYouListJson;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.ClouldChatType;
import com.jiyi.easemob.view.EasemobChatActivity;
import com.jiyi.event.HaoYouListEvent;
import com.jiyi.inteface.WebApi;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.DateUtils;
import com.swift.utils.GlideUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ClassName: ZoneTuiJianFragment
 * @Description:TODO(这里用一句话描述这个类的作用)
 * @author: HYM
 * @date: 2017-6-6 上午10:47:48
 * 
 */
public class ZoneHaoYouFragment extends Fragment implements OnRefreshListener {

	@BindView(R.id.refreshLayout)
	SwipeRefreshLayout refreshLayout;
	@BindView(R.id.mainList)
	RecyclerView mainList;
	@BindView(R.id.rlNew)
	RelativeLayout rlNew;

	@BindView(R.id.tvNull1)
	TextView tvNull1;

	List<ZoneHaoYouBean> haoYouDatas = new ArrayList<ZoneHaoYouBean>();

	HaoYouAdapter adapter;

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, Bundle savedInstanceState) {
		View view = inflater
				.inflate(R.layout.fragment_zone_haoyou, null, false);
		ButterKnife.bind(this, view);
		init();
		return view;
	}

	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		EventBus.getDefault().register(this);
	}

	@Subscribe(sticky = true)
	public void onHaoYouListEvent(HaoYouListEvent haoYouListEvent) {
		switch (haoYouListEvent.type) {
		case HaoYouListEvent.MY_HAOYOU_FRAGMENT:
			getHaoYouData();
			break;

		default:
			break;
		}
	}

	@Override
	public void onDestroy() {
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}

	/**
	 * @author: HYM
	 * @Title: init
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-6-7
	 */
	private void init() {
		setAdater();
		getHaoYouData();
	}

	private void getHaoYouData() {

		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());

		VolleyRequest.StringRequestPost(getContext(), WebApi.ZONE_HAOYOU_LIST,
				"", params, new StringInterface(getContext()) {

					@Override
					public void stringSuccess(String result) {
						if (getActivity() == null || getActivity().isFinishing()) {
							return;
						}
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								ZoneHaoYouListJson temp = new Gson().fromJson(
										result, ZoneHaoYouListJson.class);
								if (temp != null && temp.getData().size() == 0) {
									refreshLayout.setVisibility(View.GONE);
									Spannable sTextSpannable = new SpannableString(
											tvNull1.getText());
									// 改变字体颜色
									sTextSpannable
											.setSpan(
													new ForegroundColorSpan(
															getResources()
																	.getColor(
																			R.color.tab_top_on)),
													5, 10, 0);
									tvNull1.setText(sTextSpannable);
									
								} else {
									refreshLayout.setVisibility(View.VISIBLE);
									haoYouDatas.clear();
									haoYouDatas.addAll(getLastConent(temp
											.getData()));
									adapter.notifyDataSetChanged();
								}
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							refreshLayout.setRefreshing(false);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						ToastUtil.getInstances().showMsg(R.string.err_http_response);
						refreshLayout.setRefreshing(false);
					}
				});
	}

	/**
	 * @author: HYM
	 * @Title: setAdater
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-6-8
	 */
	private void setAdater() {
		// 设置refreshLayout的监听
		refreshLayout.setColorSchemeColors(Color.RED, Color.YELLOW, Color.BLUE,
				Color.GREEN);
		refreshLayout.setOnRefreshListener(this);

		LinearLayoutManager layoutManager = new LinearLayoutManager(
				getContext());
		mainList.setLayoutManager(layoutManager);
		mainList.addItemDecoration(new DividerItemDecoration(getContext(),
				DividerItemDecoration.VERTICAL_LIST, null));
		adapter = new HaoYouAdapter(haoYouDatas);
		mainList.setAdapter(adapter);
		adapter.setHaoYouItemClick(new HaoYouItemClick() {

			@Override
			public void onClick(View view, int position) {
				ZoneHaoYouBean zoneHaoYouBean = haoYouDatas.get(position);
				Intent intent2 = new Intent(getActivity(),
						EasemobChatActivity.class);
				intent2.putExtra(ClouldChatType.INTENT_USER_PIC,zoneHaoYouBean.getHead_path());
				intent2.putExtra("id", zoneHaoYouBean.getId());
				intent2.putExtra("name", zoneHaoYouBean.getName());
				intent2.putExtra("easemobgid", zoneHaoYouBean.getAccount());
				intent2.putExtra(ClouldChatType.INTENT_Group_Id, "");
				intent2.putExtra("easeMobChatType",EaseConstant.CHATTYPE_SINGLE);
				intent2.putExtra("remark_name",zoneHaoYouBean.getRemark_name());
				startActivity(intent2);

				// 把会话的消息清零
				EMConversation conversation = EMClient.getInstance()
						.chatManager()
						.getConversation(zoneHaoYouBean.getAccount());
				if (null != conversation) {
					// 指定会话消息未读数清零
					conversation.markAllMessagesAsRead();
					adapter.notifyDataSetChanged();
				}
			}
		});
//		adapter.setHaoYouItemLongClick(new HaoYouItemLongClick() {
//
//			@Override
//			public void onLongClick(View view, int position) {
//				TextView tvName = (TextView) view.findViewById(R.id.tvName);
//				ToastUtil.getInstances().showMsg(
//						tvName.getText() + "  被长按了" + position);
//			}
//		});
	}

	class HaoYouAdapter extends RecyclerView.Adapter<ViewHolder> {
		private final int TALK = 1;
		private final int NO_TALK = 2;

		List<ZoneHaoYouBean> datas;

		public HaoYouAdapter(List<ZoneHaoYouBean> datas) {
			this.datas = datas;
		}

		HaoYouItemClick haoYouItemClick;
		HaoYouItemLongClick haoYouItemLongClick;

		public void setHaoYouItemClick(HaoYouItemClick haoYouItemClick) {
			this.haoYouItemClick = haoYouItemClick;
		}

		public void setHaoYouItemLongClick(
				HaoYouItemLongClick haoYouItemLongClick) {
			this.haoYouItemLongClick = haoYouItemLongClick;
		}

		@Override
		public int getItemCount() {
			return datas.size();
		}

		@Override
		public void onBindViewHolder(ViewHolder holder, int position) {
			final ZoneHaoYouBean obj = datas.get(position);
			if (holder instanceof NoTalkHolder) {
				GlideUtil.load(getContext(), obj.getHead_path(),
						((NoTalkHolder) holder).ivLogo);
				((NoTalkHolder) holder).ivLogo
						.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								Intent intent = new Intent(v.getContext(),
										PersonInfoActivity.class);
								intent.putExtra("id", obj.getId());
								startActivity(intent);
							}
						});
				((NoTalkHolder) holder).tvName.setText(TextUtils.isEmpty(obj.getRemark_name()) ? obj.getName() : obj.getRemark_name());

			} else {
				GlideUtil.load(getContext(), obj.getHead_path(),
						((TalkHolder) holder).ivLogo);
				((TalkHolder) holder).ivLogo
						.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								Intent intent = new Intent(v.getContext(),
										PersonInfoActivity.class);
								intent.putExtra("id", obj.getId());
								startActivity(intent);
							}
						});
				((TalkHolder) holder).tvName.setText(TextUtils.isEmpty(obj.getRemark_name()) ? obj.getName() : obj.getRemark_name());
				((TalkHolder) holder).tvDate.setText(DateUtils
						.convertTimeToFormat(obj.getAccess_time()));
				Spannable smiledText = EaseSmileUtils.getSmiledText(getContext(), obj.getLastTalk());
				((TalkHolder) holder).tvLastTalk.setText(smiledText,BufferType.SPANNABLE);

				// 复用之前的小红点控件
				BadgeView badgeView = (BadgeView) ((TalkHolder) holder).ivCount
						.getTag();
				EMConversation conversation = EMClient.getInstance()
						.chatManager().getConversation(obj.getAccount());
				if (null != conversation) {
					int unReadCount = conversation.getUnreadMsgCount();
					if (unReadCount > 0) {
						if (badgeView == null) {
							badgeView = new BadgeView(getContext());
						}
						badgeView.setVisibility(View.VISIBLE);
						badgeView.setTargetView(((TalkHolder) holder).ivCount);
						badgeView.setBadgeGravity(Gravity.BOTTOM
								| Gravity.RIGHT);
						badgeView.setBadgeCount(unReadCount);
						((TalkHolder) holder).ivCount.setTag(badgeView);
					} else {
						if (badgeView != null) {
							badgeView.setVisibility(View.GONE);
						}
					}
				}

			}

		}

		@Override
		public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
			if (viewType == NO_TALK) {
				return new NoTalkHolder(LayoutInflater
						.from(parent.getContext()).inflate(
								R.layout.item_zone_haoyou_notalk, null, false));
			} else {
				return new TalkHolder(LayoutInflater.from(parent.getContext())
						.inflate(R.layout.item_zone_haoyou_talk, null, false));
			}
		}

		@Override
		public int getItemViewType(int position) {
			ZoneHaoYouBean obj = datas.get(position);
			if (TextUtils.isEmpty(obj.getLastTalk())) {
				return NO_TALK;
			}
			return TALK;
		}

		class TalkHolder extends ViewHolder implements
				OnClickListener, View.OnLongClickListener {

			RelativeLayout rlParent;
			ImageView ivLogo;
			ImageView ivCount;
			TextView tvName;
			TextView tvDate;
			TextView tvLastTalk;

			public TalkHolder(View itemView) {
				super(itemView);
				rlParent = (RelativeLayout) itemView
						.findViewById(R.id.rlParent);
				ivLogo = (ImageView) itemView.findViewById(R.id.ivLogo);
				tvName = (TextView) itemView.findViewById(R.id.tvName);
				tvDate = (TextView) itemView.findViewById(R.id.tvDate);
				tvLastTalk = (TextView) itemView.findViewById(R.id.tvLastTalk);
				ivCount = (ImageView) itemView.findViewById(R.id.ivCount);

				rlParent.setOnClickListener(this);
				rlParent.setOnLongClickListener(this);
			}

			@Override
			public void onClick(View v) {
				if (haoYouItemClick != null) {
					haoYouItemClick.onClick(v, getPosition());
				}
			}

			@Override
			public boolean onLongClick(View v) {
				if (haoYouItemLongClick != null) {
					haoYouItemLongClick.onLongClick(v, getPosition());
				}
				return true;
			}
		}

		class NoTalkHolder extends ViewHolder implements
				OnClickListener, View.OnLongClickListener {
			RelativeLayout rlParent;
			ImageView ivLogo;
			TextView tvName;

			public NoTalkHolder(View itemView) {
				super(itemView);
				rlParent = (RelativeLayout) itemView
						.findViewById(R.id.rlParent);
				ivLogo = (ImageView) itemView.findViewById(R.id.ivLogo);
				tvName = (TextView) itemView.findViewById(R.id.tvName);

				rlParent.setOnClickListener(this);
				rlParent.setOnLongClickListener(this);
			}

			@Override
			public void onClick(View v) {
				if (haoYouItemClick != null) {
					haoYouItemClick.onClick(v, getPosition());
				}
			}

			@Override
			public boolean onLongClick(View v) {
				if (haoYouItemLongClick != null) {
					haoYouItemLongClick.onLongClick(v, getPosition());
				}
				return true;
			}
		}
	}

	public interface HaoYouItemClick {
		void onClick(View view, int position);
	}

	public interface HaoYouItemLongClick {
		void onLongClick(View view, int position);
	}

	@OnClick({ R.id.rlNew })
	public void onClick(View view) {
		Intent intent = null;
		switch (view.getId()) {
		case R.id.rlNew:
			intent = new Intent(getActivity(), ZoneSearchActivity.class);
			intent.putExtra("type", 3);
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	List<ZoneHaoYouBean> getLastConent(List<ZoneHaoYouBean> temp) {
		for (ZoneHaoYouBean zoneHaoYouBean : temp) {
			EMConversation conversation = EMClient.getInstance().chatManager()
					.getConversation(zoneHaoYouBean.getAccount());
			if (conversation != null) {
				EMMessage message = conversation.getLastMessage();
				if (message != null) {
					Type type = message.getType();
					if (Type.TXT.equals(type)) {
						EMTextMessageBody body = (EMTextMessageBody) message
								.getBody();
						String msgTxt = body.getMessage();
						zoneHaoYouBean.setLastTalk(msgTxt);
					} else if (Type.IMAGE.equals(type)) {
						zoneHaoYouBean.setLastTalk("[图片]");
					} else if (Type.VOICE.equals(type)) {
						zoneHaoYouBean.setLastTalk("[语音]");
					} else if (Type.LOCATION.equals(type)) {
						zoneHaoYouBean.setLastTalk("[位置]");
					}
				}
			}
		}
		return temp;
	}

	@Override
	public void onRefresh() {
		getHaoYouData();
	}
}
